package cc.iteachyou.template.dom;

import cc.iteachyou.template.configuration.TemplateEngineConfiguration;
import cc.iteachyou.template.utils.VariableHelper;
import cn.hutool.json.JSONUtil;
import lombok.Data;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class VirtualDOMTextNode extends VirtualDOMNode {
    private String content;

    public String toString(){
        // 获取上下文中的数据
        VariableHelper variableHelper = VariableHelper.getInstance();
        Map<String, Object> templateData = variableHelper.get();

        TemplateEngineConfiguration configuration = (TemplateEngineConfiguration) templateData.get("configuration");

        Set<String> keys = templateData.keySet();
        Iterator<String> iterator = keys.iterator();
        while(iterator.hasNext()){
            String key = iterator.next();
            if((configuration.getDirectivePrefix() + "script").equals(key)){
                Pattern pattern = Pattern.compile("\\{\\{(.*?)\\}\\}");
                Matcher matcher = pattern.matcher(content);
                while (matcher.find()){
                    String group = matcher.group(1);
                    Object eval = engine.eval(group, templateData);
                    content = content.replaceFirst("\\{\\{(.*?)\\}\\}", JSONUtil.toJsonStr(eval));
                }
            }
        }
        templateData.remove(configuration.getDirectivePrefix() + "script");
        return content;
    }
}
